/*
 * Copyright (c) 2021 Shenzhen Kaihong Digital Industry Development Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import router from '@system.router'
import devm from '@ohos.distributedHardware.deviceManager';
import prompt from '@system.prompt';
import featureAbility from '@ohos.ability.featureability';

export default {
    data: {
        msg: 'world',
        devList: [],
    },
    selidx: -1,
    dev: {},
    onInit(){
        this.msg = 'hello';
        this.onStartScan();
    },
    onStartScan: function(){
        let that = this;
        devm.createDeviceManager("com.view.datashareddemo", (error, value) => {
            if (error) {
                console.error("distr createDeviceManager failed.");
                that.msg = 'create devm error.'
                return;
            }
            console.log("distr value =" +JSON.stringify(value));
            that.dev = value;
            that.msg = 'devm created.';

            var trusted = that.dev.getTrustedDeviceListSync();
            console.log('distr trusted: '+JSON.stringify(trusted));
            if (trusted){
                that.devList = trusted;
            }
            try {
                that.startSubscribe()
            }catch(e){
                console.log('distr error on start subscribe')
            }
        });
    },
    startSubscribe: function (){
        let that = this;
        this.dev.on('deviceStateChange', (data) => {
            console.info('distr deviceStateChange data=' + JSON.stringify(data));
        });
        this.dev.on('deviceFound', (data) => {
            console.log('.................................................')
            console.info('distr deviceFound data=' + JSON.stringify(data));
            that.updateDev(data.device);
        });

        var SUBSCRIBE_ID = Math.floor(65536 * Math.random());
        var info = {
            subscribeId: SUBSCRIBE_ID,
            mode: 0xAA,
            medium: 2,
            freq: 2,
            isSameAccount: false,
            isWakeRemote: true,
            capability: 0
        };
        console.info('distr startDeviceDiscover ' + SUBSCRIBE_ID);
        this.dev.startDeviceDiscovery(info);
    },
    onclick: function () {
        router.replace({
            uri: "pages/index/index"
        })
    },
    onContinuation: function (){
        console.log('distr start remote with uri.......................')
        var want = {
            bundleName: 'com.view.datashareddemo',
            abilityName: 'com.view.datashareddemo.MainAbility',
            deviceId: this.devList[this.selidx].deviceId,
            parameters: {
                isFA: 'FA',
                uri: 'pages/distr/distr'
            }
        }
        console.log(JSON.stringify(want))
        featureAbility.startAbility({
            want: want
        }).then((data)=>{
            console.log("distr myapplication: start ability finished:" + JSON.stringify(data));
        });
    },
    onStartRemote: function (uri){
        console.log('distr start remote.......................')
        var want = {
            bundleName: 'com.view.datashareddemo',
            abilityName: 'com.view.datashareddemo.MainAbility',
            deviceId: this.devList[this.selidx].deviceId,
            parameters: {
                isFA: 'FA'
            }
        }
        console.log(JSON.stringify(want))
        featureAbility.startAbility({
            want: want
        }).then((data)=>{
            console.log("distr myapplication: start ability finished:" + JSON.stringify(data));
        });
    },
    onConnectRemote: function (){
        if(this.selidx < 0){
            prompt.showToast({
                message: '没有选择远程设备',
                duration: 3000
            });
            return;
        }
        var dev = this.devList[this.selidx];
        console.log('distr ....................1'+JSON.stringify(dev))
        let extraInfo = {
            "targetPkgName": 'com.view.datashareddemo',
            "appName": 'datashareddemo',
            "appDescription": 'a test app',
            "business": '0'
        };
        let authParam = {
            "authType": 1,
            "appIcon": '',
            "appThumbnail": '',
            "extraInfo": extraInfo
        };
        try {
            this.dev.authenticateDevice(dev, authParam, (err, data) => {
                console.log("distr data ........................" + JSON.stringify(data))
                console.log("distr error........................" + JSON.stringify(err))
            });
        }catch(err){
            prompt.showToast({
                message: '认证出错了',
                duration: 3000
            });
        }
        console.log('distr ....................2')
    },
    onSelect: function(idx){
        console.log('selected '+idx);
        this.selidx = idx;
    },
    updateDev: function(dev){
        try {
            for (var i = 0; i < this.devList.length; i++) {
                if (this.devList[i].deviceId == dev.deviceId) {
                    return;
                }
            }
            this.devList.push(dev);
        }catch(err){
            console.log(err);
            console.log('distr ....................3')
            prompt.showToast({
                message: '出错了',
                duration: 3000
            });
        }
    }
}
